import 'dotenv/config';
import { drizzle } from 'drizzle-orm/libsql';
import * as schema from '~~/server/db/schema'
import { AnyColumn, eq, SQL, sql } from 'drizzle-orm';
import { AnySQLiteTable } from 'drizzle-orm/sqlite-core';

// You can specify any property from the libsql connection options
export const db = drizzle({ connection: { url: process.env.DB_FILE_NAME! }, logger: false, schema});

// export const db = drizzle(process.env.DB_FILE_NAME!);



/**
 * 创建 Drizzle ORM 查询的 where 子句
 * @param schema - Drizzle schema 对象
 * @param pojo - 查询条件对象，类型为 schema 的 $inferSelect
 * @returns 生成的 where 子句 SQL 表达式
 */
export function createWhereClause<
  T extends AnySQLiteTable<{ columns: any }>
>(
  schema: T,
  pojo: Partial<T['$inferSelect']>
): SQL | undefined {
  const whereClauses = Object.entries(pojo).reduce<SQL[]>((acc, [key, value]) => {
    if (value === undefined || value === null) {
      return acc;
    }

    // 正确访问 Drizzle 表的列定义
    const column = schema._.columns[key] as AnyColumn | undefined;
    if (column) {
      acc.push(eq(column, value as any));
    }
    return acc;
  }, []);

  return whereClauses.length > 0 
    ? sql`${whereClauses.reduce((acc, clause) => sql`${acc} AND ${clause}`)}`
    : undefined;
}